﻿/* *******************************************************************************
 * WebCamTimeLapse
 * Author: Ben Martens (webcamtimelapse@studio711.com)
 * Created: 12/21/2007
 * 
 * This is a very basic application which downloads images from the web at specified
 * intervals. When you first start the application, click the Add button and fill
 * in all the information. The list on the left side of the main form shows the name
 * of every web cam. The list on the right side is a log of every capture event.
 * 
 * To edit the settings of an existing camera, close the app, then open usersettings.xml
 * in the same directory as the exe and change the values. When you open the app next time,
 * these settings will be loaded. If you want to add some code, feel free to add an edit
 * feature.
 * 
 * A new thread is spawned on every clock tick and that thread spawns a separate thread
 * for every capture event.
 * 
 * There are many points of failure in the app, but it does what I need so I'll release
 * it like this for now. Feel free to improve it!
 * *******************************************************************************
 */

namespace WebCamTimeLapse
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Threading;

    public partial class Form1 : Form
    {
        Capture capture;
        public Form1()
        {
            InitializeComponent();
            capture = new Capture();
            RefreshList();
            capture.ImageCaptureEvent += new ImageCaptureHandler(this.ImageCapturedEventHandler);
        }

        /// <summary>
        /// An image was captured on a different thread. Write that output to the list box.
        /// </summary>
        /// <param name="message">Text to write to the log</param>
        private void ImageCapturedEventHandler(string message)
        {
            if (this.InvokeRequired)
            {
                ImageCaptureHandler theDelegateMethod = new ImageCaptureHandler(this.ImageCapturedEventHandler);
                this.Invoke(theDelegateMethod, new object[] { message });
            }
            else
            {
                lstOutput.Items.Insert(0, message);
                try
                {
                    if (lstOutput.Items.Count > 100)
                    {
                        lstOutput.Items.RemoveAt(lstOutput.Items.Count - 1);
                    }
                }
                catch { };
            }
        }

        /// <summary>
        /// Once a minute, spawn a thread to check for pictures that need to be taken.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            ThreadStart threadDelegate = new ThreadStart(capture.Tick);
            Thread newThread = new Thread(threadDelegate);
            newThread.Start();
        }

        /// <summary>
        /// Show the form to get information about the new web cam.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmAdd add = new frmAdd();
            if (add.ShowDialog() == DialogResult.OK)
            {
                capture.Add(add.Description, add.URL, Int32.Parse(add.Interval), add.LocalDirectory);
                RefreshList();
            }
        }

        /// <summary>
        /// Remove the selected web cam from the list.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemove_Click(object sender, EventArgs e)
        {
            try
            {
                int selectedIndex = lstWebCams.SelectedIndex;
                capture.RemoveAt(selectedIndex);
                RefreshList();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error removing selected web cam from the list.\nPlease make sure a web cam is selected in the list box before clicking this.\n" + ex.ToString(),
                    "Error Removing Web Cam",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// Clear the list box and refresh it with the list of web cams from the Capture class.
        /// </summary>
        private void RefreshList()
        {
            this.lstWebCams.Items.Clear();
            this.lstWebCams.Items.AddRange(capture.GetCamNames().ToArray());
        }

        /// <summary>
        /// Before the app closes, save the current list of web cams. This will record the last time that
        /// each cam was downloaded so that we don't get duplicates the next time the app is started.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            capture.CloseApp();
        }

    }
}
